const {bfmetaSDK} = require('../util/util')

const completetransferAsset = () => {
    return async (req, res, next) => {
        try {
            const words = req.body.words
            const keypair = await bfmetaSDK.bfchainSignUtil.createKeypair(words)
            const address = req.body.address;
            const publicKey = keypair.publicKey.toString('hex')
            const createResult = await bfmetaSDK.api.transaction.createTransferAsset({
                amount: "100",
                assetType: "BFMTEST",
                recipientId: address,
                publicKey: publicKey,
                fee: "2000",
                applyBlockHeight: 1,
                numberOfEffectiveBlocks: 10
            });
            if (!createResult.success) {
                throw createResult;
            }
            const buffer = createResult.result.buffer;
            const bytes = Buffer.from(buffer, "base64");
            // 生成签名
            const signature = (await bfmetaSDK.bfchainSignUtil.detachedSign(bytes, keypair.secretKey)).toString("hex");
            // 广播交易
            const broadcastResult = await bfmetaSDK.api.transaction.broadcastTransferAsset({
                buffer,
                signature,
            });
            if (!broadcastResult.success) {
                throw broadcastResult;
            }
            // 将返回交易体，交易体的格式见实际返回类型。
            console.log(broadcastResult);
        } catch (error) {
            next(error)
        }
    }
}

const transferAsset = () => {
    return (req, res, next) => {
      try {
        bfmetaSDK.api.transaction.createTransferAsset(req.body).then(result => {
          res.status(200).send(result)
        })
        console.log(req.body)
      } catch (error) {
        next(error)
      }
    }
  }
  // 2.广播模板
const broadcastTA = () => {
    return (req, res, next) => {
      try {
        bfmetaSDK.api.transaction.broadcastTransferAsset(req.body).then(result => {
          res.status(200).send(result)
        })
      } catch (error) {
        next(error)
      }
    }
}



module.exports = {transferAsset,broadcastTA,completetransferAsset}

